import React, {useEffect, useState} from 'react';
import {message, Modal, Transfer} from 'antd';
import {SecurityApi} from '@api/index'

export default (props) => {

    const [open, setOpen] = useState(false);
    const [userCode, setUserCode] = useState('')
    const [targetKeys, setTargetKeys] = useState([])
    const [dataSource, setDataSource] = useState([])

    useEffect(() => {
        setOpen(props.open)
        setUserCode(props.userCode)
    }, [props])

    useEffect(() => {
        getUserRoles()
    }, [userCode])

    const getUserRoles = async () => {
        if (userCode) {
            let ret = await SecurityApi.userRoles({code: userCode})
            if (ret && ret.code === 200) {
                let dataSource = ret.data.map(item => {
                    return {key: item.code, title: item.name}
                })
                let targetKeys = ret.data.filter(it => it.hasRole).map(item => item.code)
                setTargetKeys(targetKeys)
                setDataSource(dataSource)
            }
        }
    }

    const handleOk = async e => {
        let params = {}
        params.userCode = userCode
        params.roleCodes = targetKeys
        let ret = await SecurityApi.authz(params)
        if (ret && ret.code === 200) {
            handleCancel()
            message.success("操作成功")
        } else {
            message.error("操作失败")
        }
    };

    const handleCancel = () => {
        setOpen(false)
        props.close && props.close();
    };

    const handleChange = (nextTargetKeys, direction, moveKeys) => {
        setTargetKeys(nextTargetKeys);
    };

    return (
        <Modal
            title="用户授权"
            open={open}
            onOk={handleOk}
            onCancel={handleCancel}
            destroyOnClose="true">
            <Transfer listStyle={{width: 220, height: 350}}
                      dataSource={dataSource}
                      targetKeys={targetKeys}
                      onChange={handleChange}
                      render={item => item.title}/>
        </Modal>
    );
}
